package com.oyjd.fw.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * 获取配置文件
 * 
 * @author 欧建东
 * @email oyjd@163.com
 * 
 */
public class PropUtil {

	/**
	 * 获取配置文件
	 * 
	 * @return
	 */
	public static Map<String, String> read() {
		Map<String, String> map = new HashMap<String, String>();
		try {
			Properties p = new Properties();
			InputStream in = PropUtil.class.getResourceAsStream("/application.properties");
			p.load(in);
			for (Object key : p.keySet()) {
				String value = p.getProperty((String) key);
				map.put((String) key, value);
			}
			in.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return map;
	}

	/**
	 * 获取配置文件
	 * 
	 * @return
	 */
	public static Properties read(String path) {
		Properties p = new Properties();
		try {
			File file = new File(path);
			if (file.exists()) {
				InputStream in = new FileInputStream(file);
				p.load(in);
				in.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return p;
	}

	/**
	 * 获取配置文件
	 * 
	 * @return
	 */
	public static void write(Properties p, String path) {
		try {
			File file = new File(path);
			if (file.exists()) {
				file.delete();
			}
			OutputStream out = new FileOutputStream(file);
			p.store(out, "Auto born! Not changed!");
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		String path = "D:/application.properties";
		Properties p = read(path);
		p.put("fffff", "gggggggggg");
		p.put("flag", Boolean.toString(false));
		write(p, path);
		System.out.println(p.getProperty("jdbc.url1", "ddd"));
	}
}
